var tic = null;
var selToID = "";
var loginInfo = {};
var selType = webim.SESSION_TYPE.GROUP;
var teduBoard = null;
var TRTC = null;
var selSess = null;
var isPushCamera = true;
var enableCamera = true;
var enableMic = true;
var canUndo = "0";
var logType = "2";
var selType = webim.SESSION_TYPE.C2C; //当前聊天类型
var isIMlogin = false;
var synDrawEnable = true;

var isGetMagLogFirst = true;
var isGetMagLog = true;
var msgKey = '';
var logMsgList = [];

//默认好友头像
var friendHeadUrl = 'img/friend.jpg'; //仅demo使用，用于没有设置过头像的好友
//默认群头像
var groupHeadUrl = 'img/group.jpg'; //仅demo使用，用于没有设置过群头像的情况

//设置问诊时间
function setLogTime(time) {
  if (!isIMlogin) {
    setTimeout(() => {
      setLogTime(time)
    }, 500);
  } else {
    if (isGetMagLogFirst) {
      isGetMagLogFirst = false;
      if (!isUndefinedAndEmpty(selToID)) {
        lastMsgTime = 0; //第一次拉取好友历史消息时，必须传0
        msgKey = '';
        var logTime = new Date(time).getTime() / 1000;
        getHistoryMsgs(logTime);
      }
    }
  }
}

//获取问诊聊天消息记录
function getHistoryMsgs(logTime) {
  getLastC2CHistoryMsgs(function (msgList) {
    for (let msg of msgList) {
      if (msg.time <= logTime) {
        isGetMagLog = false;
      } else {
        if (msg.getElems()[0].type != "TIMCustomElem") {
          logMsgList.push(msg);
        }
      }
    }
    if (isGetMagLog) {
      getHistoryMsgs(logTime);
    } else {
      logMsgList.sort(function (a, b) {
        return a.time - b.time
      })
      for (let msg of logMsgList) {
        addMsg(msg)
      }
    }
  }, function (err) {
    // alert(err.ErrorInfo);
  });
}

function imTicLogin(user_type, user_id, selToID) {
  var identifier = ""
  if ("1" == user_type) {
    identifier = "U" + user_id
  } else if ("2" == user_type) {
    identifier = "S" + user_id
  } else if ("3" == user_type) {
    identifier = "D" + user_id
  }
  if (tic == null) {
    tic = new TIC

    ();
  }
  loginInfo.identifier = identifier;
  var config = genTestUserSig(loginInfo.identifier);
  loginInfo.sdkAppID = config.sdkAppID;
  loginInfo.userSig = config.userSig;
  loginInfo.userId = loginInfo.identifier;
  loginInfo.selToID = selToID;
  tic.init(loginInfo.sdkAppID, function (res) {
    if (res.code) {
      //bodytips("初始化失败！",function (){window.history.go(-1);})
      msgInfo("初始化失败！");
    } else {
      tic.login(loginInfo, loginBack);
    }
  })

  //document.getElementById("rtsytDiv").innerHTML = "";
  $("#videoDiv1").html("");
  $("#videoDiv2").html("");
}

function ticLogout(back) {
  tic.logout(back);
}

// 创建房间
function createClassroom(roomID, type) {
  if (!isIMlogin) {
    setTimeout(() => {
      createClassroom(roomID, type)
    }, 500);
  } else {
    logType = type
    if (!roomID) {
      //			bodytips('房间号不能为空');
      return;
    }
    var classOption = {
      classId: roomID,
      classScene: "0"
    };
    tic.createClassroom(classOption, function (res) {
      if (res.code) {
        if (res.code == 10021) {
          joinClassroom(roomID, logType, "#E60012")
        } else if (res.code == 10025) {
          joinClassroom(roomID, logType, "#E60012")
        } else {
          //			    	  bodytips('创建失败');
        }
      } else {
        joinClassroom(roomID, logType, "#E60012")
      }
    });
  }
}
// 加入房间
function joinClassroom(roomID, type, panColor) {
  if (!isIMlogin) {
    setTimeout(() => {
      joinClassroom(roomID, type, panColor)
    }, 500);
  } else {
    var brushColor = "#005AA8"
    if (panColor) {
      brushColor = panColor;
    }
    logType = type
    tic.joinClassroom(roomID, {}, {
      id: 'rtsytDiv',
      ratio: '16:9',
      brushColor: brushColor,
      ratio: "9:8",
      smoothLevel: 0,
      boardContentFitMode: 1
    }, res => {
      if (res.code) {
        //				  bodytips('加入失败');
      } else {
        //		    	  bodytips('加入'+roomID+'成功！');
        teduBoard = tic.getBoardInstance();
        TRTC = tic.getWebRTCInstance();
        console.log(tic)
        // // -------------------
        // let cameras = null;
        // tic.getCameras().then(devices => {
        //   cameras = devices;
        //   devices.forEach(dev => {
        //     console.log('camera label: ' + dev.label + ' deviceId: ' + dev.deviceId);
        //   });
        // });
        // // 假设本地流 localStream 已经被发布
        // // 切换到第二个摄像头
        // let cameraId = cameras[1].deviceId;
        // localStream.switchDevice('video', cameraId).then(() => {
        //   console.log('switch camera success');
        // });
        // -------------------
        initBoardEvent();
        initTRTCEvent();
        // 如果是主动推流
        if ("1" == logType) {
          startRTC();
        }
      }
    });
  }
}

//销毁房间
function destroyClassroom(roomID) {
  tic.destroyClassroom(roomID, function () {})
}

function startRTC() {
  // 获取webrtc实例
  var WebRTC = TRTC;
  WebRTC.getLocalStream({
    audio: true,
    // video: true,
    // video:{ 'facingMode': "user" },
    video: logType == '1' ? true : false,
    attributes: {
      //width: 320,
      //height: 240,
      //frameRate:20//新增参数
      width: 299,
      height: 320
    }
  }, (data) => {
    if (WebRTC.global.localStream && WebRTC.global.localStream.active) {
      WebRTC.updateStream({
        role: 'screen',
        stream: data.stream
      }, () => {
        // 成功
      }, (error) => {
        //bodytips(`更新流失败，${error}`);
      });
    } else {
      WebRTC.startRTC({
        stream: data.stream,
        role: 'user'
      }, (data) => {
        // 成功
      }, (error) => {
        //bodytips(`推流失败, ${error}`);
      });
    }
  }, (error) => {
    //bodytips("获取语音设备失败！");
  });
}


function setSelToID(val) {
  if (selToID != val) {
    selToID = val;
    loginInfo.selToID = selToID;
    teduBoard = null;
    TRTC = null;
    selSess = null;
    $("#chat_Log").html("");
  }
}

//登录成功回调
function loginBack(req) {
  var listener = {
    /**
     * 收到C2C文本消息
     * @param fromUserId		发送此消息的用户id
     * @param text				收到消息的内容
     * @param textLen			收到消息的长度
     */
    onTICRecvTextMessage: (fromUserId, text, textLen) => {
      //        	bodytips(fromUserId+""+text);
    },

    /**
     * 收到C2C自定义消息
     * @param fromUserId		发送此消息的用户id
     * @param data				收到消息的内容
     * @param dataLen			收到消息的长度
     */
    onTICRecvCustomMessage: (fromUserId, data, textLen) => {
      //        	bodytips(fromUserId+""+data);
    },

    /**
     * 收到群文本消息
     * @param fromUserId		发送此消息的用户id
     * @param text				收到消息的内容
     * @param textLen			收到消息的长度
     */
    onTICRecvGroupTextMessage: (fromUserId, text, textLen) => {},

    /**
     * 收到群自定义消息
     * @param fromUserId		发送此消息的用户id
     * @param data				收到消息的内容
     * @param dataLen			收到消息的长度
     */
    onTICRecvGroupCustomMessage: (fromUserId, data, textLen) => {
      //        	bodytips(fromUserId, data);
    },
    onTICRecvMessage(msg) {
      elems = msg.getElems()[0]; // 获取消息包含的元素数组
      content = elems.getContent(); // 获取元素对象
      type = elems.getType(); // 获取元素类型
      if (type == webim.MSG_ELEMENT_TYPE.CUSTOM) {
        var msgType = strToJson(content.getData()).type;
        if ("0" == msgType) {
          var text = strToJson(content.getData()).text;
          var onemsg = document.createElement("div");
          onemsg.className = "onemsg";
          var msghead = document.createElement("p");
          var msgbody = document.createElement("p");
          var msgPre = document.createElement("pre");
          msghead.className = "msghead";
          msgbody.className = "msgbody";
          // 如果是发给自己的消息
          msghead.style.color = "blue";
          msghead.innerHTML = webim.Tool.formatText2Html("[系统消息]" + "&nbsp;&nbsp;" + webim.Tool.formatTimeStamp(msg.getTime()));
          msgPre.innerHTML = text;
          msgbody.appendChild(msgPre);
          onemsg.appendChild(msghead);
          onemsg.appendChild(msgbody);
          var msgflow = document.getElementById("chat_Log");
          msgflow.appendChild(onemsg);
        }


        if (log_type != null) {
          if ("1" == msgType) { //医生人体示意图
            tapBtnshow2();
          }
        }

        if ("2" == msgType) { //上传图片
          $('.cklistnumred_dot').addClass('numred_dot');
          getInquiryLogImgList3()
          setTimeout(function () {
            getInquiryLogImgList3()
          }, 1000)
          setTimeout(function () {
            getInquiryLogImgList3()
          }, 2000)
          setTimeout(function () {
            getInquiryLogImgList3()
          }, 3000)
          setTimeout(function () {
            getInquiryLogImgList3()
          }, 4000)
          setTimeout(function () {
            getInquiryLogImgList3()
          }, 5000)
        }
        if ("3" == msgType) { //测量数据
          $('.cslistnumred_dot').addClass('numred_dot');
          getPatientMeasuredDataList('2')
        }

        if ("4" == msgType) { //用户退出问诊
          //            			alert(111)
          //openEditTk(28,'endbox2',1);
        }

        if ("5" == msgType) { //医生退出问诊
          //tapBtnshow("3","0");
        }
        if ("6" == msgType) { //医生开处方
          //getInquiryLogDetails_user('1');
        }
        if ("7" == msgType) { //医生填写了诊断或者开药 用户刷新接口
          //getInquiryLogDetails_user();
        }
        if ("8" == msgType) { //分诊成功
          //                		ticLogout(function (){
          //                			location.reload();
          //                		})
        }
        if ("9" == msgType) { //用户上传头像
          user_uploadImg_img()
        }
        if ("10" == msgType) { //用户人体示意图
          //openEditTk(20,'bodyHint')
        }
        if ("11" == msgType) { //医生让用户修改患者资料
          //tapBtnshow("12")
        }
        if ("12" == msgType) { //用户修改患者资料
          //user_uploadImg_img();
        }
        if ("13" == msgType) { //医生修改患者资料
          //getInquiryLogDetails_user();
        }

        if ("14" == msgType) { //手机上传图片
          $('.cklistnumred_dot').addClass('numred_dot');
          getInquiryLogImgList('1') //用户查看图片
          setTimeout(function () {
            getInquiryLogImgList('1') //用户查看图片
          }, 1000)
          setTimeout(function () {
            getInquiryLogImgList('1') //用户查看图片
          }, 2000)
          setTimeout(function () {
            getInquiryLogImgList('1') //用户查看图片
          }, 3000)
          setTimeout(function () {
            getInquiryLogImgList('1') //用户查看图片
          }, 4000)
          setTimeout(function () {
            getInquiryLogImgList('1') //用户查看图片
          }, 5000)
          //getInquiryLogImgList3()//医生查看图片
        }

      } else if (msg.getSession().id() == selToID) { // 为当前聊天对象的消息
        addMsg(msg);
      }
    }
  }
  tic.addTICMessageListener(listener)

  tic.addTICStatusListener({
    onTICForceOffline: () => {
      bodytips("账号在其他设备登录！", function () {
        ticLogout(function () {
          window.location = path_url;
          delUserLocalStorage()
        })
      })
    }
  });
  tic.addTICEventListener({
    onTICMemberJoin: (members) => {
      //          bodytips('群消息'+ members.join(',') + '进入课堂');
    },

    onTICMemberQuit: (members) => {
      //bodytips('群消息'+ members.join(',') + '退出课堂');
    },

    onTICClassroomDestroy: () => {
      //        	tic.quitClassroom(function (){
      //    			
      //    		});
    }
  });

  var tag_list = [
    "Tag_Profile_IM_Nick", //昵称
  ];
  var options = {
    'To_Account': [loginInfo.identifier],
    'TagList': tag_list
  };
  webim.getProfilePortrait(options, function (resp) {
    if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
      for (var i in resp.UserProfileItem) {
        var to_account = resp.UserProfileItem[i].To_Account;
        var nick = null,
          gender = null,
          allowType = null,
          imageUrl = null;
        for (var j in resp.UserProfileItem[i].ProfileItem) {
          switch (resp.UserProfileItem[i].ProfileItem[j].Tag) {
            case 'Tag_Profile_IM_Nick':
              nick = resp.UserProfileItem[i].ProfileItem[j].Value;
              break;
          }
        }
        loginInfo.identifierNick = webim.Tool.formatText2Html(nick)
      }
    }
    console.log(loginInfo)
  }, function (err) {
    console.log(err.ErrorInfo);
  });
  isIMlogin = true;
  selToID = loginInfo.selToID;
}

function onSendMsg() {
  if (!selToID) { // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
    alert("您还没有选中好友或者群组，暂不能聊天");
    $("#send_msg_text").val('');
    return;
  }
  //获取消息内容
  var msgtosend = $("#send_msg_text").val();
  var msgLen = webim.Tool.getStrBytes(msgtosend);
  if (msgtosend.length < 1) {
    alert("发送的消息不能为空!");
    $("#send_msg_text").val('');
    return;
  }
  var maxLen, errInfo;
  if (selType == webim.SESSION_TYPE.C2C) {
    maxLen = webim.MSG_MAX_LENGTH.C2C;
    errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
  } else {
    maxLen = webim.MSG_MAX_LENGTH.GROUP;
    errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
  }
  if (msgLen > maxLen) {
    alert(errInfo);
    return;
  }
  if (!selSess) {
    selSess = new webim.Session(selType, selToID, selToID, friendHeadUrl, Math.round(new Date().getTime() / 1000));
  }
  var isSend = true; //是否为自己发送
  var seq = -1; //消息序列，-1表示 IM SDK 自动生成，用于去重
  var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
  var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
  var subType; //消息子类型
  if (selType == webim.SESSION_TYPE.C2C) {
    subType = webim.C2C_MSG_SUB_TYPE.COMMON;
  } else {
    subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
  }
  var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, loginInfo.identifier, subType, loginInfo.identifierNick);
  msg.fromAccountHeadurl = 1;
  var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
  //解析文本和表情
  var expr = /\[[^[\]]{1,3}\]/mg;
  var emotions = msgtosend.match(expr);
  if (!emotions || emotions.length < 1) {
    text_obj = new webim.Msg.Elem.Text(msgtosend);
    msg.addText(text_obj);
  } else {
    for (var i = 0; i < emotions.length; i++) {
      tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
      if (tmsg) {
        text_obj = new webim.Msg.Elem.Text(tmsg);
        msg.addText(text_obj);
      }
      emotionIndex = webim.EmotionDataIndexs[emotions[i]];
      emotion = webim.Emotions[emotionIndex];
      if (emotion) {
        face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
        msg.addFace(face_obj);
      } else {
        text_obj = new webim.Msg.Elem.Text(emotions[i]);
        msg.addText(text_obj);
      }
      restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
      msgtosend = msgtosend.substring(restMsgIndex);
    }
    if (msgtosend) {
      text_obj = new webim.Msg.Elem.Text(msgtosend);
      msg.addText(text_obj);
    }
  }
  webim.sendMsg(msg, function (resp) {
    if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
      addMsg(msg);
    }
    $("#send_msg_text").val('');
  }, function (err) {
    alert(err.ErrorInfo);
    $("#send_msg_text").val('');
  });
}

/**
 * 发送自定义消息
 */
function sendCustomGroupMsg(type, back) {
  var data = {
    "type": type
  }
  if (back == null) {
    tic.sendCustomMessage(selToID, jsonToStr(data), function (res) {
      console.log('===sendCustomGroupMsg:', res);
    });
  } else {
    tic.sendCustomMessage(selToID, jsonToStr(data), back);
  }
}

/**
 * 发送自定义消息
 */
function sendSystemMessageMsg(text) {
  var data = {
    "type": "0",
    "text": text
  }
  tic.sendCustomMessage(selToID, jsonToStr(data), function (res) {
    console.log('===sendCustomGroupMsg:', res);
  });
}

// 添加一条消息显示
function addMsg(msg, prepend) {
  var isSelfSend, fromAccount, fromAccountNick, fromAccountImage, sessType, subType;
  // 获取会话类型，目前只支持群聊
  // webim.SESSION_TYPE.GROUP-群聊，
  // webim.SESSION_TYPE.C2C-私聊，
  sessType = msg.getSession().type();

  isSelfSend = msg.getIsSend(); // 消息是否为自己发的
  fromAccount = msg.getFromAccount();
  if (!fromAccount) {
    return;
  }
  if (isSelfSend) { // 如果是自己发的消息
    if (loginInfo.identifierNick) {
      //fromAccountNick = $(".myName").html();
      fromAccountNick = userName;
    } else {
      fromAccountNick = "自己";
    }
  } else { // 如果别人发的消息
    var key = webim.SESSION_TYPE.C2C + "_" + fromAccount;
    if (msg.getFromAccountNick()) {
      fromAccountNick = doctorName;
      //fromAccountNick = $(".otherNames").html();
    } else {
      fromAccountNick = "陌生人";
    }
  }

  var onemsg = document.createElement("div");
  if (msg.sending) {
    onemsg.id = "id_" + msg.random;
    // 发送中
    var spinner = document.createElement("div");
    spinner.className = "spinner";
    spinner.innerHTML = '<div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div>';
    onemsg.appendChild(spinner);
  } else {
    $("#id_" + msg.random).remove();
  }
  onemsg.className = "onemsg";
  var msghead = document.createElement("p");
  var msgbody = document.createElement("p");
  var msgPre = document.createElement("pre");
  msghead.className = "msghead";
  msgbody.className = "msgbody";
  // 如果是发给自己的消息
  if (!isSelfSend)
    msghead.style.color = "blue";
  // 昵称 消息时间
  msghead.innerHTML = webim.Tool.formatText2Html("[" + fromAccountNick + "]" + "&nbsp;&nbsp;" + webim.Tool.formatTimeStamp(msg.getTime()));
  // 获取消息子类型
  // 会话类型为群聊时，子类型为：webim.GROUP_MSG_SUB_TYPE
  // 会话类型为私聊时，子类型为：webim.C2C_MSG_SUB_TYPE
  msgPre.innerHTML = convertMsgtoHtml(msg);
  msgbody.appendChild(msgPre);
  onemsg.appendChild(msghead);
  onemsg.appendChild(msgbody);
  // 消息列表
  var msgflow = document.getElementById("chat_Log");
  if (prepend) {
    $("#chat_Log").prepend(onemsg);
    // 300ms后,等待图片加载完，滚动条自动滚动到底部
    setTimeout(function () {
      msgflow.scrollTop = msgflow.scrollHeight;
    }, 300);
  } else {
    $("#chat_Log").append(onemsg);
    // 300ms后,等待图片加载完，滚动条自动滚动到底部
    setTimeout(function () {
      msgflow.scrollTop = msgflow.scrollHeight;
    }, 300);
  }
}

// 把消息转换成Html
function convertMsgtoHtml(msg) {
  var html = "",
    elems, elem, type, content;
  elems = msg.getElems(); // 获取消息包含的元素数组
  for (var i in elems) {
    elem = elems[i];
    type = elem.getType(); // 获取元素类型
    content = elem.getContent(); // 获取元素对象
    switch (type) {
      case webim.MSG_ELEMENT_TYPE.TEXT:
        html += convertTextMsgToHtml(content);
        break;
      case webim.MSG_ELEMENT_TYPE.CUSTOM:
        html += convertCustomMsgToHtml(content);
        break;
      default:
        html += convertTextMsgToHtml(content);
        break;
    }
  }

  return webim.Tool.formatHtml2Text(html);
}

// 解析文本消息元素
function convertTextMsgToHtml(content) {
  return content.getText();
}

// 解析自定义消息元素
function convertCustomMsgToHtml(content) {
  var data = content.getData();
  var desc = content.getDesc();
  var ext = content.getExt();
  return "data=" + data + ", desc=" + desc + ", ext=" + ext;
}

// 返回 01-12 的月份值
function getMonth(date) {
  var month = "";
  month = date.getMonth() + 1; // getMonth()得到的月份是0-11
  if (month < 10) {
    month = "0" + month;
  }
  return month;
}
// 返回01-30的日期
function getDay(date) {
  var day = "";
  day = date.getDate();
  if (day < 10) {
    day = "0" + day;
  }
  return day;
}
// 返回小时
function getHours(date) {
  var hours = "";
  hours = date.getHours();
  if (hours < 10) {
    hours = "0" + hours;
  }
  return hours;
}
// 返回分
function getMinutes(date) {
  var minute = "";
  minute = date.getMinutes();
  if (minute < 10) {
    minute = "0" + minute;
  }
  return minute;
}
// 返回秒
function getSeconds(date) {
  var second = "";
  second = date.getSeconds();
  if (second < 10) {
    second = "0" + second;
  }
  return second;
}

//监听音视频事件（按需监听）
function initTRTCEvent() {
  TRTC.on('onLocalStreamAdd', (data) => {
    if (data && data.stream) {
      enableCamera ? TRTC.openVideo() : TRTC.closeVideo();
      enableMic ? TRTC.openAudio() : TRTC.closeAudio();

      var localVideoEl = document.getElementById('doctor_video');
      if (!localVideoEl) {
        localVideoEl = document.createElement('video');
        localVideoEl.id = 'local_video';
        localVideoEl.class = "col-md-1";
        $("#videoDiv1").html("");
        document.querySelector("#videoDiv1").appendChild(localVideoEl);
        console.log(data);
      }
      localVideoEl.muted = true;
      localVideoEl.autoplay = true;
      localVideoEl.setAttribute('autoplay', true);
      localVideoEl.setAttribute('playsinline', true);
      localVideoEl.srcObject = data.stream;
      //bodytips('WebRTC接收到本地流');
    }
  })

  TRTC.on('onRemoteStreamUpdate', (data) => {
    var userVideoEl = document.getElementById(data.videoId);
    if (!userVideoEl) {
      userVideoEl = document.createElement('video');
      userVideoEl.id = data.videoId;
      userVideoEl.class = "col-md-1";
      $("#videoDiv2").html("");
      document.querySelector("#videoDiv2").appendChild(userVideoEl);
      console.log(data);
    }
    userVideoEl.setAttribute('autoplay', true);
    userVideoEl.setAttribute('playsinline', true);
    userVideoEl.srcObject = data.stream;

    //bodytips('WebRTC接收到远端流');
  })

  TRTC.on('onRemoteStreamRemove', (data) => {
    var userVideoEl = document.getElementById(data.videoId);
    if (userVideoEl) {
      userVideoEl.remove();
    }
    //bodytips('WebRTC 远端流断开');
  })

  TRTC.on('onWebSocketClose', (data) => {
    //bodytips('WebRTC WebSocket 断开');
  })

  TRTC.on('onRelayTimeout', (data) => {
    //bodytips('WebRTC 超时');
  })

  TRTC.on('onStreamNotify', (data) => {
    //console.log('==================== onStreamNotify==', data);
  })

  TRTC.on('onMuteVideo', (data) => {
    // bodytips(`${data.userId}关闭了摄像头`);
    // console.log('==================== onMuteVideo==', data);
  })

  TRTC.on('onUnmuteVideo', (data) => {
    //bodytips(`${data.userId}打开了摄像头`);
    //console.log('==================== onUnmuteVideo==', data);
  })

  TRTC.on('onMuteAudio', (data) => {
    //      bodytips(`${data.userId}关闭了麦克风`);
    // console.log('==================== onMuteAudio==', data);
  })

  TRTC.on('onUnmuteAudio', (data) => {
    //      bodytips(`${data.userId}打开了麦克风`);
    //console.log('==================== onUnmuteAudio==', data);
  })
}

// 监听白板事件（按需监听）
function initBoardEvent() {
  // 撤销状态改变
  teduBoard.on(TEduBoard.EVENT.TEB_OPERATE_CANUNDO_STATUS_CHANGED, (enable) => {
    canUndo = enable ? 1 : 0;
    console.log('======================:  ', 'TEB_OPERATE_CANUNDO_STATUS_CHANGED', enable ? '可撤销' : '不可撤销');
  });

  // 重做状态改变
  teduBoard.on(TEduBoard.EVENT.TEB_OPERATE_CANREDO_STATUS_CHANGED, (enable) => {
    canRedo = enable ? 1 : 0;
    console.log('======================:  ', 'TEB_OPERATE_CANREDO_STATUS_CHANGED', enable ? '可恢复' : '不可恢复');
  });

  // 新增白板
  teduBoard.on(TEduBoard.EVENT.TEB_ADDBOARD, (boardIds, fid) => {
    console.log('======================:  ', 'TEB_ADDBOARD', ' boardIds:', boardIds, ' fid:', fid);
    //proBoardData();
  });

  // 白板同步数据回调(收到该回调时需要将回调数据通过信令通道发送给房间内其他人，接受者收到后调用AddSyncData接口将数据添加到白板以实现数据同步)
  // TIC已经处理好了，可忽略该事件
  teduBoard.on(TEduBoard.EVENT.TEB_SYNCDATA, (data) => {
    teduBoard.addSyncData(data)
    console.log('======================:  ', 'TEB_SYNCDATA');
  });

  // 收到白板初始化完成事件后，表示白板已处于正常工作状态（此时白板为空白白板，历史数据尚未拉取完成）
  teduBoard.on(TEduBoard.EVENT.TEB_INIT, () => {
    console.log('======================:  ', 'TEB_INIT');
    //showMessageInBox('TIC', "onTEBInit finished");
  });

  teduBoard.on(TEduBoard.EVENT.TEB_HISTROYDATA_SYNCCOMPLETED, () => {
    console.log('======================:  ', 'TEB_HISTROYDATA_SYNCCOMPLETED');
    //showMessageInBox('TIC', "onTEBHistory Sync Completed finished");
  });

  // 白板错误回调
  teduBoard.on(TEduBoard.EVENT.TEB_ERROR, (code, msg) => {
    console.error('======================:  ', 'TEB_ERROR', ' code:', code, ' msg:', msg);
    //showMessageInBox('TIC', "onTEBError code=" + code + " msg:" + msg);
  });

  // 白板警告回调
  teduBoard.on(TEduBoard.EVENT.TEB_WARNING, (code, msg) => {
    console.error('======================:  ', 'TEB_WARNING', ' code:', code, ' msg:', msg);
    //showMessageInBox('TIC', "onTEBWarning code=" + code + " msg:" + msg);
  });

  // 图片状态加载回调
  teduBoard.on(TEduBoard.EVENT.TEB_IMAGE_STATUS_CHANGED, (status, data) => {
    console.log('======================:  ', 'TEB_IMAGE_STATUS_CHANGED', ' status:', status, ' data:', data);
  });

  // 删除白板页回调
  teduBoard.on(TEduBoard.EVENT.TEB_DELETEBOARD, (boardIds, fid) => {
    console.log('======================:  ', 'TEB_DELETEBOARD', ' boardIds:', boardIds, ' fid:', fid);
    //proBoardData();
  });

  // 跳转白板页回调
  teduBoard.on(TEduBoard.EVENT.TEB_GOTOBOARD, (boardId, fid) => {
    console.log('======================:  ', 'TEB_GOTOBOARD', ' boardId:', boardId, ' fid:', fid);
    //proBoardData();
  });

  // 增加H5动画PPT文件回调
  teduBoard.on(TEduBoard.EVENT.TEB_ADDH5PPTFILE, (fid) => {
    console.log('======================:  ', 'TEB_ADDH5PPTFILE', ' fid:', fid);
    //proBoardData();
  });

  // 增加文件回调
  teduBoard.on(TEduBoard.EVENT.TEB_ADDFILE, (fid) => {
    console.log('======================:  ', 'TEB_ADDFILE', ' fid:', fid);
    //proBoardData();
  });

  // 增加转码文件回调
  teduBoard.on(TEduBoard.EVENT.TEB_ADDTRANSCODEFILE, (fid) => {
    console.log('======================:  ', 'TEB_ADDTRANSCODEFILE', ' fid:', fid);
    //proBoardData();
  });

  // 删除文件回调
  teduBoard.on(TEduBoard.EVENT.TEB_DELETEFILE, (fid) => {
    console.log('======================:  ', 'TEB_DELETEFILE', ' fid:', fid);
    //proBoardData();
  });

  // 文件上传状态
  teduBoard.on(TEduBoard.EVENT.TEB_FILEUPLOADSTATUS, (status, data) => {
    console.log('======================:  ', 'TEB_FILEUPLOADSTATUS', status, data);
    if (status === 1) {
      this.showTip('上传成功');
    } else {
      this.showTip('上传失败');
    }
    document.getElementById('file_input').value = '';
  });

  // 切换文件回调
  teduBoard.on(TEduBoard.EVENT.TEB_SWITCHFILE, (fid) => {
    console.log('======================:  ', 'TEB_SWITCHFILE', ' fid:', fid);
    //proBoardData();
  });

  // 上传背景图片的回调
  teduBoard.on(TEduBoard.EVENT.TEB_SETBACKGROUNDIMAGE, (fileName, fileUrl, userData) => {
    console.log('======================:  ', 'TEB_SETBACKGROUNDIMAGE', '  fileName:', fileName, '  fileUrl:', fileUrl, ' userData:', userData);
  });

  // 文件上传进度
  teduBoard.on(TEduBoard.EVENT.TEB_FILEUPLOADPROGRESS, (data) => {
    console.log('======================:  ', 'TEB_FILEUPLOADPROGRESS:: ', data);
    //showTip('上传进度:' + parseInt(data.percent * 100) + '%');
  });

  // H5背景加载状态
  teduBoard.on(TEduBoard.EVENT.TEB_H5BACKGROUND_STATUS_CHANGED, (status, data) => {
    console.log('======================:  ', 'TEB_H5BACKGROUND_STATUS_CHANGED:: status:', status, '  data:', data);
  });
}


function setBackgroundImage() {
  if (teduBoard == null) {
    bodytips("没有加入网络问诊页面！")
    return false;
  }
  sendCustomGroupMsg("1");
  teduBoard.setBackgroundImage(path_url + "form_mobile/util/imgs/sketchmap.png");
  return true;
}



//切换 笔和橡皮擦
function onSetToolType(type) {
  if (teduBoard == null) {
    return;
  }
  var toolType = TEduBoard.TOOL_TYPE.TEDU_BOARD_TOOL_TYPE_PEN
  if ("2" == type) {
    toolType = TEduBoard.TOOL_TYPE.TEDU_BOARD_TOOL_TYPE_ERASER;
  }
  teduBoard.setToolType(toolType);
}

//清空白板
function onclearDraws() {
  if (teduBoard == null) {
    return;
  }
  teduBoard.clear();
}

/**
 * 摄像头开关
 */
function toggleCamera() {
  enableCamera = !enableCamera;
  enableCamera ? TRTC.openVideo() : TRTC.closeVideo();
  enableCamera == true ? jQuery('.toggleCamera').text('关闭摄像头') : jQuery('.toggleCamera').text('打开摄像头')
}

/**
 * 麦克风开关
 */
function toggleMic() {
  enableMic = !enableMic
  enableMic ? TRTC.openAudio() : TRTC.closeAudio();
  enableMic == true ? jQuery('.toggleMic').text('关闭麦克风') : jQuery('.toggleMic').text('打开麦克风')
}


var getLastC2CHistoryMsgs = function (cbOk, cbError) {
  var options = {
    'Peer_Account': selToID, //好友帐号，selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
    'MaxCnt': 15, //拉取消息条数
    'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
    'MsgKey': msgKey
  };
  webim.getC2CHistoryMsgs(
    options,
    function (resp) {
      var complete = resp.Complete; //是否还有历史消息可以拉取，1表示没有，0表示有
      var retMsgCount = resp.MsgCount; //返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了
      if (resp.MsgList.length == 0) {
        webim.Log.error("没有历史消息了:data=" + JSON.stringify(options));
        return;
      }
      lastMsgTime = resp.LastMsgTime;
      msgKey = resp.MsgKey;
      if (cbOk)
        cbOk(resp.MsgList);
    },
    cbError
  );
};